<template>
  <div>
    <main-layout>
      <template v-slot:top>
        <el-form ref="searchForm" :inline="true" :model="searchInfo">
          <el-form-item label="用户ID">
            <el-input v-model="searchInfo.miguUid" placeholder="用户ID" clearable />
          </el-form-item>
          <el-form-item label="手机号码">
            <el-input v-model="searchInfo.phone" placeholder="手机号码" clearable />
          </el-form-item>
          <el-form-item label="消耗事项">
            <el-input v-model="searchInfo.actionName" placeholder="消耗事项" clearable />
          </el-form-item>
          <el-form-item label="消耗时间">
            <el-date-picker v-model="time" type="datetimerange" range-separator="至" start-placeholder="开始时间"
              end-placeholder="结束时间" value-format="YYYY-MM-DD HH:mm:ss"/>
          </el-form-item>
          <el-form-item label="绿色能量数值变化">
            <div class="inputLine">
              <el-input v-model="searchInfo.energyAmountStart" clearable /><s>g</s>
              <span class="zhi">至</span>
              <el-input v-model="searchInfo.energyAmountEnd" clearable /><s>g</s>
            </div>
          </el-form-item>

          <!-- <el-form-item label="类型">
            <el-select v-model="searchInfo.type" clearable placeholder="请选择" style="width: 140px;">
              <el-option :value="1" label="普通用户" />
              <el-option :value="2" label="经销商" />
              <el-option :value="3" label="系统管理员" />
            </el-select>
          </el-form-item> -->

          <el-form-item>
            <el-button size="small" type="primary" icon="search" @click="onSubmit">查询</el-button>
            <el-button size="small" icon="refresh" @click="onReset">重置</el-button>
          </el-form-item>
        </el-form>
      </template>

      <auth-tag code="greenEnergy:export">
        <div class="gva-btn-list">
          <popover-botton text="导出" icon="download" :lists="[{id:1,label:'全部导出'},{id:2,label:'导出选中数据'}]" @itemClick="exportExcel"/>
        </div>
      </auth-tag>

      <c-table ref="tableRef" :page="{ pageSize, pageIndex, total }" :lists="tableData" @current-change="handleCurrentChange"
        @size-change="handleSizeChange" :loading="loading" showCheck @selection-change="selectionChange" rowKey="greenEnergyId">
        <el-table-column align="center" label="用户ID" min-width="150" prop="miguUid" />
        <el-table-column align="center" label="手机号" min-width="110" prop="phone" />
          <!-- <template #default="scope">
            {{ phoneReplace(scope.row.phone) }}
          </template>
        </el-table-column> -->
        <el-table-column align="center" label="绿色能量数值变化" min-width="120" prop="energyAmount" />
        <el-table-column align="center" label="事项" min-width="120" prop="actionName"/>
        <el-table-column align="center" label="发生时间" min-width="120" >
          <template #default="scope">
            {{ formatDateLong(scope.row.createTime) }}
          </template>
        </el-table-column>
      </c-table>

    </main-layout>

  </div>
</template>

<script setup>
import { nextTick, ref, watch, onActivated,reactive } from 'vue'
import {getGreenEnergyList,greenEnergyExportAll} from '@/api/user'
import { ElMessageBox } from 'element-plus'

import mainLayout from '@/components/custom/mainLayout.vue'
import cTable from '@/components/custom/cTable.vue'
import popoverBotton from '@/components/custom/popoverBotton.vue'

import {formatDateLong,phoneReplace,formatDate} from '@/utils/format'

import { useUserStore } from '@/pinia/modules/user'
import {exportToExcel} from '@/utils/exportExcel'
import {message} from '@/utils/element'
import { emitter } from '@/utils/bus.js'

const userStore = useUserStore()
onActivated(() => {
  console.log('-----onActivated------', userStore.pageInit)
  if (userStore.pageInit) { // 需要刷新页面
    init()
  } else if (userStore.refreshFn) { // 刷新函数存在，在执行
    userStore.refreshFn()
  }
})


const pageIndex = ref(1)
const total = ref(0)
const pageSize = ref(10)
const tableData = ref([])
const searchInfo = ref({})
const time = ref('')
const loading = ref(true)
const tableRef = ref(null)


const init = () => {
  pageIndex.value = 1
  onReset()
  getTableData()
}

const onReset = () => {
  searchInfo.value = {}
  time.value = ''
}
// 搜索
const onSubmit = () => {
  pageIndex.value = 1
  tableRef.value.clear_selection()  // 清空所选
  getTableData()
}
// 分页
const handleSizeChange = (val) => {
  pageIndex.value = 1
  pageSize.value = val
  getTableData()
}

const handleCurrentChange = (val) => {
  pageIndex.value = val
  getTableData()
}

// 查询
const getTableData = async () => {
  if(time.value){
    searchInfo.value.createTimeStart = time.value[0]
    searchInfo.value.createTimeEnd = time.value[1]
  }
  const res = await getGreenEnergyList({ page: pageIndex.value, size: pageSize.value, ...searchInfo.value })
  if (res.code === 200) {
    tableData.value = res.data
    total.value = res.total
  }
  if(res.status==403){
    ElMessageBox.confirm('无权访问','提示',
      {
          confirmButtonText: '确定',
          showCancelButton:false,
          type: 'warning',
      }).then(async () => {
        emitter.emit('closeThisPage') // 关闭当前页面
      })
  }
  loading.value = false
}

let tableCheckeds = []
const selectionChange= (items)=>{
  tableCheckeds = items
}

const exportExcel = async (o)=>{
  let exportData = []
  const fileName = `${formatDate(new Date())} 绿色能量管理`.replace(/-/g,"")
  if(o.id == 2){
    if(!tableCheckeds.length){
      return message('请选择需要导出的数据',3)
    }
    exportData = tableCheckeds
  }else{
    console.log("全部导出")
    const res = await greenEnergyExportAll()
    const file = new Blob([res], { type: res.type})
    const url = URL.createObjectURL(file);
    const a = document.createElement("a");
    a.setAttribute("download",`${fileName}.xlsx`); 
    a.href = url;
    a.click();
    

    //*******************以下但也可以导出，但不能重命名*****************************
    // let blob = new Blob([res], { type: res.type});
    // let objectUrl = URL.createObjectURL(blob);
    // window.location.href = objectUrl


    return
    // const res = await getGreenEnergyList({ page: 1, size: 1000})
    // if (res.code === 200) {
    //   exportData = res.data
    // }else{
    //   return message('获取数据出错了，请重试',3)
    // }
  }
  console.log("生成文件...")

  const headers = ["序号", '用户ID', '手机号', "绿色能量数值变化", "事项", "发生时间"]
  let lists =[] //[[1,'1985-02-15','tom1','地址1'],[2,'2001-05-20','tom2','地址2']]
  exportData.forEach((item, index) =>{
    const arr = [
      index + 1,
      item.miguUid,
      item.phone,
      item.energyAmount,
      item.actionName,
      formatDateLong(item.createTime)
    ]
    lists.push(arr)
  })
  

  exportToExcel(fileName,headers,lists)
}


</script>

<style lang="scss" scoped>
.inputLine {
  display: flex;
  width: 200px;
  .zhi{
    padding: 0 10px;
  }
  s{
    font-style: normal;
    text-decoration: none;
    padding: 0 0 0 5px;
    color: var(--el-text-color-regular);
  }
}
</style>
